package com.epalmpay.handler;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.epalmpay.dto.member.SubscribeMemberDTO;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.service.weixin.IWxApiMemberService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.BaseWxService;
import com.epalmpay.util.Tools;
import com.github.binarywang.java.emoji.EmojiConverter;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 用户关注公众号Handler
 * <p>
 * Created by FirenzesEagle on 2016/7/27 0027.
 * Email:liumingbo2008@gmail.com
 */
@Component
public class SubscribeHandler extends AbstractHandler {
	
	public @Value("${PAY.HOME_URL}") 
	String HOME_URL;//项目路径 带项目名称
	public @Value("${PAY.ROOT_HOME_URL}") 
	String ROOT_HOME_URL;//项目路径不 带项目名称

	@Resource
	private IWxBaseService wxBaseService;
	
	@Resource 
	private IWxApiMemberService wxApiMemberService;
	
	private EmojiConverter emojiConverter = EmojiConverter.getInstance();

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
    		WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
    	this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
    	this.logger.info("主页url: " + ROOT_HOME_URL);
        BaseWxService weixinService = (BaseWxService) wxMpService;
        WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), "zh_CN");
        this.logger.info("新关注用户 昵称: " + userWxInfo.getNickname());
        String nickname=this.emojiConverter.toAlias(userWxInfo.getNickname());
		try {
			String eventKey=wxMessage.getEventKey();
			String content=null;
			if(Tools.notEmpty(eventKey)){
				this.logger.info("场景值: " + eventKey);
				//获取场景值并截取
				String event_Key = eventKey.substring(eventKey.indexOf("_") + 1);
				SubscribeMemberDTO subscribeMember=wxBaseService.savesubscribe(wxMessage.getToUser(),event_Key, userWxInfo,nickname);
				switch (BizEnum.ScancrcodeType.fromType(subscribeMember.getType())) {
						case subscribe:
							 if(subscribeMember.getFlag()){
								 content=wxApiMemberService.subscribeMember(ROOT_HOME_URL, subscribeMember, nickname, "邀请");
							 }else{
								 content=wxApiMemberService.subscribeUrl(HOME_URL, subscribeMember, nickname,userWxInfo.getOpenId());
							 }
							break;
						case agentSubscribe:
							content=wxApiMemberService.subscribeUrl(HOME_URL, subscribeMember, nickname,userWxInfo.getOpenId());
							break;
						case ShopsubScribe:
							content=wxApiMemberService.subscribeUrl(HOME_URL, subscribeMember, nickname,userWxInfo.getOpenId());
							break;	
						case memberSubscribe:
							if(subscribeMember.getFlag()){
								 content=wxApiMemberService.subscribeMember(ROOT_HOME_URL, subscribeMember, nickname, "邀请");
							 }else{
								content=wxApiMemberService.subscribeUrl(HOME_URL, subscribeMember, nickname,userWxInfo.getOpenId());		
							     wxApiMemberService.insertInviteMember(subscribeMember.getGroupId(), subscribeMember.getSourceId(), subscribeMember.getMemberId());	
							 }
							break;	
						case posConsumeSend:
							 if(subscribeMember.getFlag()){
								 content=wxApiMemberService.subscribeSendEnvelope(ROOT_HOME_URL, subscribeMember, nickname, "领取");
							 }else{
								 content=wxApiMemberService.subscribeUrl(HOME_URL, subscribeMember, nickname,userWxInfo.getOpenId());
							 }
							break;	
						case posRedEnvelope:
							if(subscribeMember.getFlag()){
								 content=wxApiMemberService.subscribeSendEnvelope(ROOT_HOME_URL, subscribeMember, nickname, "领取");
							 }else{
								 content=wxApiMemberService.subscribeUrl(HOME_URL, subscribeMember, nickname,userWxInfo.getOpenId());
							 }
							break;	
						default:
							break;
					  }
			}else{
					 SubscribeMemberDTO subscribeMember=wxBaseService.savesubscribe(wxMessage.getToUser(),null, userWxInfo,nickname);
					 if(subscribeMember.getFlag()){
						 content=wxApiMemberService.subscribeMember(ROOT_HOME_URL, subscribeMember, nickname, "邀请");
					 }else{
						 content=wxApiMemberService.subscribeUrl(HOME_URL, subscribeMember, nickname,userWxInfo.getOpenId());
					 }
			}
			  WxMpXmlOutTextMessage xm
	            = WxMpXmlOutMessage.TEXT()
	            .content(content)
	            .fromUser(wxMessage.getToUser())
	            .toUser(wxMessage.getFromUser())
	            .build();
	        logger.info("subscribeMessageHandler" + xm.getContent());
	        return xm;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }
};
